package cmd

import (
	"io/ioutil"

	"gitee.com/shaddy/k3sinstall/install"
	"gitee.com/shaddy/k3sinstall/mylog"
	"github.com/spf13/cobra"
	"gopkg.in/yaml.v2"
)

var (
	PkgPath  string
	imageCmd = &cobra.Command{
		Use:   "image",
		Short: "Simplest way to add image to your k3s HA cluster",
		Long:  `k3sinstall image --pkg`,
		Run: func(cmd *cobra.Command, args []string) {
			y, err := ioutil.ReadFile(ConfigFile)
			if err != nil {
				mylog.Error.Panicf("read config file %s failed %w", ConfigFile, err)
			}
			config := &install.K3sConfig{}
			err = yaml.Unmarshal(y, config)
			if err != nil {
				mylog.Error.Panicf("unmarshal config file failed: %w", err)
			}
			install.InstallImage(config, PkgPath)

		},
		PreRun: func(cmd *cobra.Command, args []string) {
			if PkgPath == "" {
				cmd.Help()
				mylog.Error.Panicf("缺失参数pkg指定")
			}
			home, err := Home()
			if err != nil {
				mylog.Error.Panicf("获取Home目录失败 %s", err.Error())
			}
			ConfigHome = home
			if !FileExist(home + "/.k3sinstall") {
				mylog.Error.Panicf("can not find config file , is install k3s cluster ?")

			}
			ConfigFile = home + "/.k3sinstall/config.yaml"
		},
	}
)

func init() {
	imageCmd.Flags().StringVar(&PkgPath, "pkg", "/root/pkg.tar", "image path to install")
}
